/**
 * 修改商品信息
 */
function updateProductData(){
    var name = $("input[name = updateProductName]").val();
    var describe = $("input[name = updateProductDescribe]").val();
    var stock = $("input[name = updateProductStock]").val();
    var sellingPrice = $("input[name = updateProductSellingPrice]").val();
    var purchasingPrice = $("input[name = updateProductPurchasingPrice]").val();
    var a={
        "id": id,
        "name": name,
        "describe": describe,
        "stock": stock,
        "sellingPrice": sellingPrice,
        "purchasingPrice": purchasingPrice,
    };
    $.ajax({
        type:"PUT",
        url: "/product/updateProduct",
        data:JSON.stringify(a),
        contentType: 'application/json;charset=UTF-8',
        success: function (result) {
            $('#updateProduct').modal('hide');
            refreshProductData();
        },
        error:function(e){
            console.log(e.status);
            console.log(e.responseText);
            alert("操作有误请联系管理员")
        }
    })
}

function updateProductDialog(vo){
    $('#updateProduct').modal('show');
    id=vo.id;
    $("input[name=updateProductName]").val(vo.name);
    $("input[name=updateProductDescribe]").val(vo.describe);
    $("input[name=updateProductStock]").val(vo.stock);
    $("input[name=updateProductSellingPrice]").val(vo.sellingPrice);
    $("input[name=updateProductPurchasingPrice]").val(vo.purchasingPrice);

    $('#updateProductImage').attr("src",vo.image)
}


/**
 * 查看商品信息
 * @param data
 */
function queryImg(data) {
//前端获取
    $('#showProduct').modal('show');
    $('#ProductList tbody').on('click', 'tr', function () {
        $('#showProductName').text(data.name);
        $('#showProductDescribe').text(data.describe);
        $('#showProductStock').text(data.stock);
        $('#showProductSellingPrice').text(data.sellingPrice);
        $('#showProductPurchasingPrice').text(data.purchasingPrice);
        $('#showProductStatus').text(data.status);
        $('#showProductSales').text(data.sales);
        $('#showProductCreateTime').text(data.createTime);
        $('#showProductUpdateTime').text(data.updateTime);
        //为<img>标签添加src，用来显示商品照片
        $('#showProductImage').attr("src",data.image)
    } );
}


/**
 * 上架已有商品
 */
function putAwayProduct(id){
    $('#putAwayProduct').modal('show');
    productId = id;
}
$('#putAwayProductButton').on('click',function(){
    $.ajax({
        type:"DELETE",
        url:"/product/putAwayProduct?id="+productId,
        success:function(result){
            $('#putAwayProduct').modal('hide');
            refreshProductData();
        },
        error:function(e){
            console.log(e.status);
            console.log(e.responseText);
            alert("操作有误请联系管理员！")
        }
    })
})

/**
 * 下架商品
 */
var productId;
function soldOutProduct(id){
    $('#soldOutProduct').modal('show');
    productId = id;
}
$('#soldOutProductButton').on('click',function(){
    $.ajax({
        type:"DELETE",
        url:"/product/soldOutProduct?id="+productId,
        success:function(result){
            $('#soldOutProduct').modal('hide');
            refreshProductData();
        },
        error:function(e){
            console.log(e.status);
            console.log(e.responseText);
            alert("操作有误请联系管理员！")
        }
    })
})


/**
 * 上架新商品
 */
function addProductDialog() {
    $('#addProduct').modal('show');
}

function showImg(cell) {
    baseImg= window.URL.createObjectURL(cell.files[0]);
    console.log("baseImg:"+baseImg)
}

function image2Base64(img) {//转base64的方法
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL;
}

function addProduct() {
    var name = $("input[name = addProductName]")[0].value;
    var describe = $("input[name = addProductDescribe]")[0].value;
    var stock = $("input[name = addProductStock]")[0].value;
    var sellingPrice = $("input[name = addProductSellingPrice]")[0].value;
    var purchasingPrice = $("input[name = addProductPurchasingPrice]")[0].value;
    var kindId = $("input[name = addProductKindId]")[0].value;
    var formData = new FormData();
    formData.append("file",$('#addProductImage')[0].files[0])
    formData.append("name",name)
    formData.append("describe",describe)
    formData.append("stock",stock)
    formData.append("sellingPrice",sellingPrice)
    formData.append("purchasingPrice",purchasingPrice)
    formData.append("kindId",kindId)
    console.log("id='"+id+"'name='"+name+"' describe='"+describe+"' stock='"+stock+"' sellingPrice='"+sellingPrice+"' purchasingPrice='"+purchasingPrice+"kindId='"+kindId+"'")
    $.ajax({
        // 请求方式
        type: "POST",
        // 请求地址
        url: "/product/addProduct",
        // contentType: 'application/json;charset=UTF-8',
        // 数据
        data: formData,
        processData : false,
        contentType : false,
        success: function (result) {
            $('#addProduct').modal('hide');
            refreshProductData();
            console.log(result)
        },
        // 请求失败，包含具体的错误信息
        error: function (e) {
            console.log(e.status);
            console.log(e.responseText);
            alert("请填写完整的商品信息！")
        }
    });
}


/**
 * 获取商品信息列表
 * @param query
 */
function getProductData(query) {
    $('#ProductList')
        .DataTable(
            {
                "destroy": true,
                // "searching":false,
                "pagingType": "full_numbers",
                "sLoadingRecords": "正在加载数据...",
                "sZeroRecords": "暂无数据",
                "ajax": {
                    url: "/product/getProductList",
                    // dataSrc: 'data',//原来为空，修改为data 因为服务端模式返回的是data入参
                    dataSrc: "",
                    type:"post",
                    data : query,
                },
                // "serverSide": true,//服务端分页
                // "lengthChange": false,//是否允许用户自定义显示数量
                // "scrollY": "360px",//竖向滚动条
                // "scrollCollapse": "true",//是否出现滚动条
                // 'iDisplayLength':10,
                "searching": true,
                "columns": [
                    {
                        "data": "id"
                    },
                    {
                        "data": "name"
                    },
                    {
                        "data": "describe"
                    },
                    {
                        "data": "stock"
                    },
                    {
                        "data": "sellingPrice"
                    },
                    {
                        "data": "purchasingPrice"
                    },
                    {
                        "data": "status"
                    },
                    {
                        "data": "sales"
                    },
                    {
                        "data": "createTime"
                    },
                    {
                        "data": "updateTime"
                    },
                    {
                        "data": null,
                        "render": function (data, type, row, meta) {
                            var obj = JSON.stringify(data).replace(/\"/g,"'");
                            var html = "<a  href='#' role='button' data-toggle='modal' class='btn btn-success btn-xs btn-green' onclick='updateProductDialog("
                                + JSON.stringify(row)
                                + ")'><i class='fa fa-pencil' ></i>修改</a>    "

                                + '<a href="#" role="button" data-toggle="modal" class=\'btn btn-success btn-xs btn-green\' onclick="queryImg('
                                +obj
                                + ')"><i class="fa fa-trash-o"  ></i>查看</a>  '

                                + '<a href="#" role="button" data-toggle="modal" class=\'btn btn-warning btn-xs btn-remove\' onclick="putAwayProduct('
                                + row.id
                                + ')"><i class="fa fa-trash-o"  ></i>上架</a>  '

                                + '<a href="#" role="button" data-toggle="modal" class=\'btn btn-danger btn-xs btn-remove\' onclick="soldOutProduct('
                                + row.id
                                + ')"><i class="fa fa-trash-o"  ></i>下架</a>  ';

                            return html;
                        }
                    }
                ],
                "language": {
                    "processing": "玩命加载中...",
                    "lengthMenu": "显示 _MENU_ 项结果",
                    "zeroRecords": "没有匹配结果",
                    "info": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                    "infoEmpty": "显示第 0 至 0 项结果，共 0 项",
                    "infoFiltered": "(由 _MAX_ 项结果过滤)",
                    "infoPostFix": "",
                    "url": "",
                    "paginate": {
                        "first": "首页",
                        "previous": "前一页",
                        "next": "下一页",
                        "last": "末页"
                    }
                }
            });
}


/**
 * 刷新
 */
function refreshProductData(){
    var b={
        "id":$('#searchProductId').val() !="" ? $("#searchProductId").val():0,
        'name':$('#searchProductName').val(),
        'sellingPrice':$('#searchProductSellingPrice').val(),
        'purchasingPrice':$('#searchProductPurchasingPrice').val(),
        'stock':$('#searchProductStock').val(),
        'describe':$('#searchProductDescribe').val(),
        // "limit":1,
        // "page":1
    };
    $.ajax({
        // 请求方式
        type: "post",
        // 请求地址
        url: "/product/getProductList",
        data: JSON.stringify(b),
        contentType: 'application/json;charset=UTF-8',
        // 请求成功
        success: function (result) {
            b.recordsTotal=result;
            getProductData(b);
        },
        // 请求失败，包含具体的错误信息
        error: function (e) {
            console.log(e.status);
            console.log(e.responseText);
            alert("操作有误请联系管理员")
        }
    });
}

